package com.mac.common.util;

import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;

public class TableExpTxtTask {
	/**
	 * 日志记录
	 */
	private final Logger logger =  LoggerFactory.getLogger(this.getClass());

	private static String FTP_FILE_PATH = "/app/dbank/cms/uploadFiles/";

	private String bankCode;

	/**
	 * 初始化查询Sql
	 */
	private List<String[]> initSqlList() {
		List<String[]> sqlList = new ArrayList<String[]>();
		String sql = "select m.convertid,m.gettime,m.bankcode,m.convertcode,m.rewardcode,m.inputtime from reward_convert_info m".toUpperCase();
		String[] tables = {"REWARD_CONVERT_INFO", "3011", sql};
		sqlList.add(tables);
		return sqlList;
	}

	@RequestMapping("/test")
	public Map logic(String bankCode) {
		logger.info("============== EXPTXT TASK START ====================");
		Map<String,Object> returnMap  = new HashMap<String,Object>();
		try {
			this.bankCode = bankCode;
			long startTime = System.currentTimeMillis();
			// 初始化参数
			List<String[]> sqlList = initSqlList();
			// 处理数据
			for (String[] sql : sqlList) {
				logger.info("=====> START OF " + sql[0]);
				startExp(sql);
				logger.info("=====> END OF " + sql[0]);
			}
			long endTime = System.currentTimeMillis();
			logger.info("============== EXPTXT TASK OVER ====================");
			logger.info("============= EXECUTE TIME: " + (endTime - startTime) + "ms ====================");
			returnMap.put("RUNSTATE", "01");
		} catch (Exception e) {
			logger.error("============== EXPTXT TASK ERROR ====================");
			logger.error("错误信息：" + e);
			returnMap.put("RUNSTATE", "02");
			e.printStackTrace();

		}
		return returnMap;
	}

	/**
	 * 执行写入操作
	 * @param sql 数组：sql[0]: 文件名，sql[1]: 银行号, sql[2]: 需要执行的sql
	 */
	private void startExp (String[] sql) throws Exception {
 		String tableName = sql[0];
		String bankCode = sql[1];
		// 当前页
		Integer currentPage = 1;
		// 页显示大小
		Integer pageSize = 1000;
		Date date = new Date();
		// 当前日期，（当天）
		String nowDate = String.valueOf(date.getTime()).replaceAll("-", "");
		String filePath = FTP_FILE_PATH + bankCode + "/td/" + nowDate + "/";
		filePath = filePath.trim();
		logger.info(">>>>>>> filePath : " + filePath);
		mkdir(filePath);
		String fileName = tableName + "_" + nowDate + ".txt";
		logger.info("开始生成TXT文件,文件名为【{}】", fileName);
		PageInfo<Map<String, Object>> dataList = null;
		// 分页导出数据
		do {
			dataList = null;//iExpTxtDataService.queryExpTxtData(sql[2], currentPage, pageSize);
			writeInfoToTXT(dataList.getList(), filePath + fileName);
			currentPage = dataList.getNextPage();
			dataList.getList().clear();
		} while (dataList.isHasNextPage());

		logger.info("TXT文件已生成,文件名为【{}】", fileName);
	}

	/**
	 * 写入文件
	 * @param listMap 需要写入的数据
	 * @param outputFileName 文件名
	 */
	private void writeInfoToTXT(List<Map<String, Object>> listMap, String outputFileName) throws Exception {
		FileWriter writer = null;
		try {
			writer = new FileWriter(outputFileName,true);
			if(null != listMap && listMap.size() > 0) {
				StringBuffer sb = null;
				for(Map<String, Object> map : listMap) {
					sb = new StringBuffer();
					for (String key : map.keySet()) {
						if("ROW_ID".equals(key.toUpperCase())) {
							continue;
						}
						sb.append(map.get(key)).append(",");
					}
					writer.write(sb.toString().substring(0, sb.length() -1));
					writer.write("\r\n");
				}
			}
		} catch (IOException e1) {
			logger.error("写入TXT文件失败，文件路径：{}", outputFileName);
			throw new IOException();
		} finally {
			if (null != writer) {
				try {
					writer.close();
				} catch (IOException e) {
					logger.error("关闭文件流失败，文件路径：{}", outputFileName);
					e.printStackTrace();
					throw new IOException();
				}
			}
		}
	}

	/**
	 * 创建文件夹
	 * @param fileDir 文件名
	 * @return boolean
	 */
	public boolean mkdir(String fileDir){
		boolean flag = false;
		File file = new File(fileDir);
		if(!file.exists()) {
			flag = file.mkdirs();
		}
		return flag;
	}
	
}
